﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace Remindme
{
    public sealed partial class MainPage
    {
        HttpClient httpClient;
        string requestToken;

        public MainPage()
        {
            this.InitializeComponent();
            this.httpClient = new HttpClient();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        async protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            AppUtils.SettingsManager settings = App.Current.Resources["Settings"] as AppUtils.SettingsManager;
            if (!settings.AccessTokenSetting.Equals(""))
            {
                var dataContext = this.DataContext as ViewModel.MainViewModel;
                if (!dataContext.IsDataLoaded)
                    await dataContext.LoadDataAsync();
                base.OnNavigatedTo(e);
                return;
            }

            string resString = String.Empty;
            Uri endUri = Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

            try
            {
                // Contenido de la petición, enviado como una cadena urlencoded
                List<KeyValuePair<string, string>> reqParams = new List<KeyValuePair<string, string>>();

                reqParams.Add(new KeyValuePair<string, string>("consumer_key", Other.Secrets.WIN8_CONSUMER_KEY));
                reqParams.Add(new KeyValuePair<string, string>("redirect_uri", endUri.ToString()));

                HttpContent reqContent = new FormUrlEncodedContent(reqParams);

                // Hago la petición POST y recupero la respuesta con el request token
                HttpResponseMessage response = await this.httpClient.PostAsync("https://getpocket.com/v3/oauth/request", reqContent);
                response.EnsureSuccessStatusCode();
                resString = await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException hre)
            {
                Debug.WriteLine(hre.Message + ": " + hre.StackTrace);
            }
            finally
            {
                base.OnNavigatedTo(e);
            }

            if (resString.Equals(String.Empty))
                return;

            // Divido la cadena por el = y cojo el segundo elemento (el request token)
            string[] data = resString.Split('=');
            requestToken = data[1];

            string result;

            Uri startUri = new Uri("https://getpocket.com/auth/authorize?request_token=" + requestToken + "&redirect_uri=" + endUri.ToString() + ":authorizationFinished&webauthenticationbroker=1");

            try
            {
                var webAuthenticationResult =
                    await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync(
                        Windows.Security.Authentication.Web.WebAuthenticationOptions.None,
                        startUri,
                        endUri
                    );

                switch (webAuthenticationResult.ResponseStatus)
                {
                    case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success:
                        result = webAuthenticationResult.ResponseData.ToString();
                        await ObtainAccessCodeAsync();
                        break;
                    case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp:
                        result = "Error: " + webAuthenticationResult.ResponseErrorDetail.ToString();
                        break;
                    default:
                        result = "Otro error: " + webAuthenticationResult.ResponseData.ToString();
                        break;
                }
            }
            catch (Exception ex)
            {
                result = "Exception: " + ex.Message;
            }
            finally
            {
                base.OnNavigatedTo(e);
            }
        }

        async System.Threading.Tasks.Task ObtainAccessCodeAsync()
        {
            string resString = String.Empty;
            AppUtils.SettingsManager settings = App.Current.Resources["Settings"] as AppUtils.SettingsManager;

            try
            {
                // Contenido de la petición, enviado como una cadena urlencoded
                List<KeyValuePair<string, string>> reqParams = new List<KeyValuePair<string, string>>();

                reqParams.Add(new KeyValuePair<string, string>("consumer_key", Other.Secrets.WIN8_CONSUMER_KEY));
                reqParams.Add(new KeyValuePair<string, string>("code", requestToken));

                HttpContent reqContent = new FormUrlEncodedContent(reqParams);
                Debug.WriteLine(await reqContent.ReadAsStringAsync());
                // Hago la petición POST y recupero la respuesta con el request token
                HttpResponseMessage response = await this.httpClient.PostAsync("https://getpocket.com/v3/oauth/authorize", reqContent);
                response.EnsureSuccessStatusCode();
                resString = await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException hre)
            {
                Debug.WriteLine(hre.Message + ": " + hre.StackTrace);
            }

            string accessToken = resString.Split('&')[0].Split('=')[1];
            string userName = resString.Split('&')[1].Split('=')[1];

            settings.AccessTokenSetting = accessToken;
            settings.UserNameSetting = userName;
        }
    }
}
